
package com.xwyzsn.rentcar.service;
import com.xwyzsn.rentcar.entity.Car;
import com.xwyzsn.rentcar.mapper.CarMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Map;
import java.lang.reflect.Field;
import java.util.Date;

@Service
public class CarService  {

    @Autowired
    private CarMapper carMapper;
    public List<Car> getOne(Map<String,?>payload){
        if (payload.isEmpty()){
            return carMapper.getAll();
        }
        Integer id = (Integer) payload.get("id");
        return carMapper.getOne(id);
    }

    public Boolean addOne(Map<String,?>payload){
        if (payload.isEmpty())return false;
        Car car = setEntity(payload,Car.class);
        return carMapper.addOne(car);
    }

    public Boolean deleteOne(Map<String,?>payload){
        Integer id = (Integer) payload.get("id");
        return carMapper.deleteOne(id);
    }

    public Integer updateOne(Map<String,?>payload){
        Car car = setEntity(payload,Car.class);
        return carMapper.updateOne(car);
    }

    public static <T> T setEntity(Map<String, ?> payload, Class<T> clazz) {
        try {
            T entity = clazz.newInstance();
            Field[] fields = clazz.getDeclaredFields();

            for (Field field : fields) {
                String fieldName = field.getName();
                if (payload.containsKey(fieldName)) {
                    field.setAccessible(true);
                    Object value = payload.get(fieldName);

                    // Handle type conversions if necessary
                    if (field.getType() == Integer.class ) {
                        value = Integer.valueOf((String) value);
                    } else if (field.getType() == Double.class ) {
                        value = Double.valueOf((String) value);
                    } else if (field.getType() == Date.class) {
                        value = new Date();
                    }else if (field.getType() == String.class ){
                        value = (String) value;
                    }
                    field.set(entity, value);
                }
            }
            return entity;
        } catch (InstantiationException | IllegalAccessException e) {
            e.printStackTrace(); // Handle or log the exception as needed
            return null;
        }
    }
}

